# MysqlStoredProcs
module MysqlStoredProcs
  VIEW_ROOT = File.join(RAILS_ROOT, "db", "procedures")

  def self.reinitialize_procs
    delete_procs
    add_procs
  end

  def self.add_procs
    fake_view = ActionView::Base.new([VIEW_ROOT])
    File.open(File.join(RAILS_ROOT, "db", "schema_procedures.sql"), "w") do |procs_file|
      proc_names.each do |proc_name|
        puts "Creating #{proc_name}"
        sql = fake_view.render(:file => "#{proc_name}.sql.erb")
        procs_file.write("#{sql}\n")
        ActiveRecord::Base.connection.execute(sql)
      end
    end
  end

  def self.delete_procs
    proc_names.each do |proc_name|
      puts "Dropping #{proc_name}"
      ActiveRecord::Base.connection.execute("DROP PROCEDURE IF EXISTS #{proc_name}")
    end
  end

  private

  def self.proc_names
    filenames = Dir.glob(File.join(VIEW_ROOT, "**", "*.sql.erb"))
    filenames.collect{|fn| File.basename(fn, ".sql.erb") }
  end
end